{include file="public/header" /}
{load href="__PLUGINS__bootstrap/bootstrap-table.min.css"}
{load href="__PLUGINS__bootstrap/bootstrap-table.min.js"}
<style >
    #des, #des input {
        width: 40px;
        text-align: center;
    }

    #id {
        width: 78px;
    }

    .bs-checkbox {
        width: 36px;
        height: 40px
    }

    .fixed-table-toolbar .columns, .fixed-table-toolbar .search {
        margin-left: 0px;
        margin-top: 0px
    }

    #title span {
        float: right;
    }

    .asdlkjasd {
        background: #1ab394;
        color: #fff
    }

    td {
        word-wrap: break-word;
        word-break: break-all;
        max-width: 700px;
    }
</style>
<body class="gray-bg">
<div class="wrapper wrapper-content">
    <div class="ibox float-e-margins">
        {include file="public/tophead"}
        {include file="public/top" /}
        <div class="ibox-content">
            {include file="public/topsection"}
            <div class="row row-lg">
                <div class="col-sm-12">
                    <div class="fixed-table-toolbar">
                        <form  method="get" action="" style="display: flex;">
                            <div class="pull-left search" style="display: flex;">
                                <div class="columns columns-right btn-group pull-left">
                                    <select class="form-control" name="search">
                                        <option value="userid" {php}if(input('?param.search')){if(input('param.search')=='userid'){echo "selected";} }{/php}>用户ID</option>
                                        <option value="data" {php}if(input('?param.search')){if(input('param.search')=='data'){echo "selected";} }{/php}>内容</option>
                                        <option value="touserid" {php}if(input('?param.search')){if(input('param.search')=='touserid'){echo "selected";} }{/php}>接收方用户ID</option>
                                    </select>
                                </div>

                                <div class="pull-right search">
                                    <input class="form-control input-outline" type="text"
                                           {php}
                                           if(input('?param.name')){
                                    if(input('param.name')){
                                    echo "value='".input('name')."'";
                                    }

                                    }
                                    {/php}
                                    name="name" placeholder="输入双方ID，用,隔开">
                                </div>

                                <div class="pull-right search">
                                    <button style="border-radius:0px; border:1px solid #e5e6e7; border-left:0px" class="btn btn-default btn-outline" type="submit" id="search-btn">搜索</button>
                                </div>

                                <input name="start" type="text" id="start" class="form-control layui-input" value="{present name='start'}{$start}{/present}" placeholder=" # 起始时间" autocomplete="off" style="height:34px;width:180px;margin:0 10px;">
                                <input name="end" type="text" id="end" class="form-control layui-input" value="{present name='end'}{$end}{/present}" placeholder=" # 结束时间" autocomplete="off" style="height:34px;width:180px;margin:0 10px;">

                                {php}
                                if(input('?param.name')){
                                {/php}
                                <div class="pull-right search">
                                    <a class="btn btn-w-m btn-link" href="{:url('record_audio')}">返回列表</a>
                                </div>{php}
                                }
                                {/php}
                            </div>
                        </form>
                    </div>
                    <div class="example">
                        <form class="form-horizontal" method="post">
                        <table data-toggle="table">
                            <thead>
                            <tr>
                                <th class="bs-checkbox"><input type="checkbox" id="delidAll"></th>
                                <th data-align="center">ID</th>
                                <th data-align="center">发送方</th>
                                <!--<th data-align="center">    </th>-->
                                <th data-align="center">接收方</th>
                                <th>内容</th>
                                <th data-align="center">转文字</th>
                                <th data-align="center">时间</th>
                                <th data-align="center">管理</th>
                            </tr>
                            </thead>
                            <tbody id="form">
                                {php}
                                $riskUsers = db('user_risk')->where(['end_time'=>0])->column('user_id');
                                $selectUsers = db('select_users')->column('user_id');
                                {/php}
                            {volist name="data" id="v"}
                            <tr id="id{$v.id}" class="class">
                                <td id="delid" ><input name="delAll[]" type="checkbox" value="{$v.id}"></td>
                                <td>{$v.id}</td>
                                <td>
                                    {php}
                                    $userinfo = _user_cache($v['userid'], 'name,is_banned,sex');
                                    {/php}
                                    <a onClick="add('{:url('member/index',['search'=>'id','name'=>$v['userid']])}')" style="color:#40BCF7">{$userinfo['name']} {$userinfo['is_banned']?'<span style="color: red;">(已封号)</span>':''}{:in_array($v['userid'], $riskUsers)?'<span style="color: red;">(风控)</span>':''}{:in_array($v['userid'], $selectUsers)?'<span style="color: red;">(精选)</span>':''}</a><br > ({$v.userid})({$userinfo['sex']})
                                </td>
                                <!--<td>>>>></td>-->
                                <td>
                                    {php}
                                    $touserinfo = _user_cache($v['touserid'], 'name,is_banned,sex');
                                    {/php}
                                    <a onClick="add('{:url('member/index',['search'=>'id','name'=>$v['touserid']])}')" style="color:#40BCF7">{$touserinfo['name']} {$touserinfo['is_banned']?'<span style="color: red;">(已封号)</span>':''}{:in_array($v['touserid'], $riskUsers)?'<span style="color: red;">(风控)</span>':''}</a> <br > ({$v.touserid})({$touserinfo['sex']})
                                </td>
                                <td>
                                    <audio src="{:strpos($v.content, 'http')===false?'__ROOT__':''}{$v.content}" controls="controls">Your browser does not support the audio element.</audio>

                                    {php}echo $v['is_fate'] ? '<span style="color:#490">[招呼语]</span>' : '';
                                    {/php}

                                </td>
                                <td id="tostring{$v.id}">

                                    {php}
                                        $jsondata = json_decode($v['data'], true);
                                        $str = $jsondata['text'] ?? '';
                                    {/php} 
                                    {if condition="$str"}
                                    {$str}
                                    {else/}
                                    <div class="btn btn-xs btn-warning" onclick="tostring('{:strpos($v.content, 'http')===false?'__ROOT__':''}{$v.content}', 'tostring{$v.id}')">转文字</div>
                                    {/if}
                                </td>
                                <td>{$v.addtime}</td>
                                    <td>
                                        <a onclick="chat('{$v.userid},{$v.touserid}')" style="color:#40BCF7">查看对话</a>
                                    <div class="btn-group">
                                        <div data-toggle="dropdown" class="btn btn-primary btn-xs dropdown-toggle">操作 <span class="caret"></span>
                                        </div>
                                        <ul class="dropdown-menu">
                                            <li><a onClick="del({$v.id})">删除单条</a></li>
                                        </ul>
                                    </div>
                                </td>
                            </tr>
                            {/volist}
                            </tbody>
                        </table>
                        </form>
                    </div>
                </div>
            </div>
            <hr>
            <div class="row row-lg">
                <div class="col-sm-6">
                    <div  class="btn btn-outline btn-default" onclick="alla('del')">
                        批量删除
                    </div>
                </div>
                <div class="col-sm-12 pages">{$page}</div>
            </div>
        </div>
    </div>
</div>
<div id="LianmaiDetail" style="text-align:center;display:none;margin: 0px 30px;padding:10px 100px">
</div>
<div id="OrderDetail" style="text-align:center;display:none;margin: 0px 30px;padding:10px 100px">
</div>
<script type="text/javascript">
    $(document).ready(function(){
        $('#delidAll').click(function(){
            $('input[type=checkbox]').each(function(){
                var self=$(this);
                if(!self.prop('checked')){
                    self.prop('checked',true);
                }else{
                    self.prop('checked',false);
                }
            });
        })
    });
    var formatDateString = (date) => {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, "0");
      const day = String(date.getDate()).padStart(2, "0");
      return `${year}-${month}-${day}`;
    };

    var nowTime=new Date();
    var lastday = new Date() //当天
        lastday.setMonth(lastday.getMonth()-6)//三个月前，时间戳
    var tomorrow = new Date() //当天
    tomorrow.setDate(tomorrow.getDate() + 1);


    layui.use(['laydate'], function(){
        var laydate = layui.laydate;

        laydate.render({
            elem: '#start' //指定元素
            ,type: 'datetime'
            ,trigger: 'click',
            max:'nowTime',//默认最大值为当前日期
            min:formatDateString(lastday)
        });

        laydate.render({
            elem: '#end' //指定元素
            ,type: 'datetime'
            ,trigger: 'click',
            max:formatDateString(tomorrow),
            min:formatDateString(lastday)
        });
    })


    function del(id){
        swal_del(id,"{:url('pdel')}")
    }
    function delalls(id, reset = 0){
        swal_delAll({id},"{:url('delalls')}?reset=" + reset, 1)
    }

    function alla(){
        return newAllDel()

        var all = $(".form-horizontal").serialize();

        ajaxFun("post",'{:url("delAll")}',all,'json',function(ret){
            if(ret){
                swal_msg('操作成功')
                window.location.reload();
            }
        })
    }
    function newAllDel() {
        const alls = $(".form-horizontal").serializeArray();
        const idsToDelete = alls.map(item => item.value);

        // 使用 Promise.all 来处理所有 AJAX 请求
        Promise.all(idsToDelete.map(id => deleteById(id)))
            .then(results => {
                const delLen = results.filter(result => result).length;
                swal_msg(`已删除${delLen}条`, '', '', 1);
            })
            .catch(error => {
                console.error('删除过程中发生错误:', error);
                swal_msg('删除过程中发生错误，请重试。', '', '', 1);
            });
    }

    function deleteById(id) {
        return new Promise((resolve, reject) => {
            $.ajax({
                type: 'POST',
                url: "{:url('admin/usertalk/pdel')}",
                data: { id: id },
                dataType: 'json',
                success: function (data) {
                    resolve(data.ret);
                },
                error: function (jqXHR, textStatus, errorThrown) {
                    console.error('请求失败:', textStatus, errorThrown);
                    reject(textStatus);
                }
            });
        });
    }

    function chat(uids)
    {
        layui.use('layer', function(){
            var layer = layui.layer;
            layer.open({
                title :'预览',
                area: ['100%', '100%'],
                type: 2,
                content: '{:url("usertalk/records")}?search=userid&d=1&name='+uids
            });
        });
    }

    var toing = false

    function tostring(url, id) {
        if (toing) {
            return layer.msg('请勿快速点击');
        }
                    
        toing = true
        $.ajax({
            type: 'POST',
            url: "{:url('admin/usertalk/tostring')}",
            data: { url },
            dataType: 'json',
            success: function (data) {
                toing = false
                console.log(data);
                if (data.err) {
                    return layer.msg(data.err)
                } else {
                    $(`#${id}`).html(data.ret)
                }
            },
            error: function (jqXHR, textStatus, errorThrown) {
                toing = false
                console.error('请求失败:', textStatus, errorThrown);
                reject(textStatus);
            }
        });
    }
</script>
{include file="public/footer" /}

